/*
 * @(#)NIOAcceptor.java	1.0 Mar 8, 2008
 *
 *	The MIT License
 *
 *	Copyright (c) 2008 Malachi de AElfweald <malachid@gmail.com>
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
package org.eoti.net.nio;

import static org.eoti.util.log.LogUtil.*;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

public class NIOAcceptor<ATTACHMENT>
		extends Thread
{
	protected NIOServer<ATTACHMENT>	server;
	protected ServerSocketChannel serverSocketChannel;
	protected InetSocketAddress socketAddress;
    protected boolean				dead = true;

	public NIOAcceptor(NIOServer<ATTACHMENT> server)
	throws NIOException
	{
		super("NIOAcceptor");
		this.server = server;
		try{
			serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.configureBlocking(false);
			socketAddress = new InetSocketAddress(server.getPortConfiguration().getPort());
			ServerSocket socket = serverSocketChannel.socket();
			socket.setReuseAddress(true);
			socket.bind(socketAddress);
			serverSocketChannel.register(server.getAcceptSelector(), SelectionKey.OP_ACCEPT);
			dead = false;
		}catch(Exception e){
			throw new NIOException(e);
		}
	}

	public NIOServer<ATTACHMENT> getServer(){return server;}
	public ServerSocketChannel getServerSocketChannel(){return serverSocketChannel;}
	public InetSocketAddress getSocketAddress(){return socketAddress;}

	public void die()
	throws IOException
	{
		dead = true;
		serverSocketChannel.close();
	}

	public void run()
	{
		while(!dead)
		{
			try{
				/**
			     * Timeout may not be necessary, but thought this might be a
			     * little more likely to prevent deadlock.
			     */
		    	server.getAcceptSelector().select(server.getTimeoutMS());
		    	acceptPendingConnections();
		    }catch(Exception e){
				log("NIOAcceptor: Error while accepting connections.", e);
		    }
		}
	}

	protected void acceptPendingConnections()
	throws NIOException
	{
		try{
			Set<SelectionKey> readyKeys = server.getAcceptSelector().selectedKeys();
            for(SelectionKey key : readyKeys)
			{
				readyKeys.remove( key );
				acceptPendingConnection(key);
			}

		}catch(NIOException ne){
			throw ne;
	    }catch(Exception e){
	    	throw new NIOException(e);
	    }
	}

	protected void acceptPendingConnection(SelectionKey key)
			throws NIOException
	{
		try{
			ServerSocketChannel serverChannel = (ServerSocketChannel)key.channel();
			SocketChannel clientChannel = serverChannel.accept();
			Socket socket = clientChannel.socket();
            if(socket == null)
			{
				warning("NIOAcceptor: Connection from NULL");
			}else{
				InetAddress address = socket.getInetAddress();
				if(address == null)
					warning("NIOAcceptor: Connection no longer connected.");
				else
					info("NIOAcceptor: Connection from " + address);
			}

			// should we only do this if we have a correct address?
			server.getConnections().add(clientChannel);
			server.getReadSelector().wakeup();
	    }catch(Exception e){
	    	throw new NIOException(e);
	    }
	}
}
